class Solution {
public:
    vector<vector<int>> fourSum(vector<int>& nums, int target)
    {
        vector<vector<int>> vv;
        int n = nums.size();
        sort(nums.begin(), nums.end());
        int a = 0;
        while (a < n - 3)
        {
            int b = a + 1;
            while (b < n - 2)
            {
                int l = b + 1, r = n - 1;
                long long aim = (long long)target - nums[a] - nums[b];
                while (l < r)
                {
                    long long sum = nums[l] + nums[r];
                    if (sum == aim)
                    {
                        vv.push_back({ nums[a], nums[b], nums[l], nums[r] });
                        l++, r--;
                        while (l < r && nums[l] == nums[l - 1]) l++;
                        while (l < r && nums[r] == nums[r + 1]) r--;
                    }
                    else if (sum < aim) l++;
                    else r--;
                }
                b++;
                while (b < n - 2 && nums[b] == nums[b - 1]) b++;
            }
            a++;
            while (a < n - 3 && nums[a] == nums[a - 1]) a++;
        }
        return vv;
    }
};